<?php
namespace app\pc\controller;
use service\CacheService;
use service\JsonService;
use service\SystemConfigService;
use service\UtilService;
use think\Cookie;
use think\Config;
use think\Db;
use think\Request;
use think\Session;
use think\Url;
use app\pc\model\tindex\Catehome as catehomemodel;
use app\pc\model\tindex\Tcategory as tcatemodel;
use app\pc\model\tindex\Tquestion as tque;
use app\pc\model\tindex\Tjiucuo as jiucuo;
use app\pc\model\tindex\Tbiji as biji;
use app\pc\model\tindex\Tcuoti as cuoti;
use app\pc\model\tindex\Tcollect as collect;
use app\wap\model\user\User;
//
use app\pc\model\tindex\Ytcategory as ytcatemodel;
use app\pc\model\tindex\Ytquestion as ytque;
use app\pc\model\tindex\Tmenu;


use app\pc\model\tindex\Tlianxi;
use app\pc\model\tindex\Tcollect as Fav;
class Tindex extends AuthController
{

    protected $tquelimit=150;
  /*
  * 白名单
  * */
  public static function WhiteList()
  {
      return [
          'subitem',
          'index',
          'question',
          'gettque',//需要登录
          'sindex'
      ];
  }
    protected function _initialize()
    {
    
        parent::_initialize();
        $this->cateid=$cateid=$this->request->param('cateid');
        $this->isopen();
        

        /*如果数据还没有导入跳转到默认类*/
        $dbfix=Config::get('database')['prefix'];
        $exist=Db::query("show tables like '".$dbfix.$this->item["fix"]."_tcate'");
        if(!$exist){
            Cookie::set('cateid', 9);
            $this->cateid=$cateid=9;
            $this->item=catehomemodel::getinfos(9);
        }
    }

    public function index()
    {
        $catelist=catehomemodel::getAll(array("parentid"=>0,'limit'=>10));
        $this->assign('catelist',$catelist);
        return $this->fetch();
    }
    public  function sindex($pid)
    {
        $Catedata=catehomemodel::getAll(array("parentid"=>'','limit'=>1881));
        $catelist=$this->getTreeson($this->getTree($Catedata,$pid,0));
       
        $this->assign('catehtml',$catelist);
 
        return $this->fetch();
    }

    public function start()
    {
        if(empty(Cookie::get('cateid')))
        {
            $url=Url::build('tindex/index');
            Header("Location: $url");
        }
        
        $id=$this->cateid;

        $item=$this->item;
        $catelist=tcatemodel::getAllarr(array("parentid"=>$item["mocateid"],'limit'=>30),$item["fix"]);
        $tm=Tmenu::getAll(array("cateid"=>$id,'kehuduan'=>0,"limit"=>10));
        $this->assign('item',$item);
        $this->assign('id',$id);
        $this->assign('catelist',$catelist);
        $this->assign('fix',$item["fix"]);
        
        $this->assign("tquetotal",tque::gettotal($item["fix"]));
        $this->assign("bijitotal",biji::gettotal($this->uid));
        $this->assign("shoucangtotal",collect::gettotal($this->uid));
        $this->assign("cuotitotal",cuoti::gettotal($this->uid));
        $this->assign('tm',$tm);
        return $this->fetch();
    }
    //练习
    public function tlist(){
        $id=$this->cateid;
        $item=$this->item;
        $fix=$item["fix"];
        $zid=$this->request->param('zid');

        $tcatelist=tcatemodel::getAll(array("parentid"=>0,'limit'=>30),$fix);
        if(empty($zid)){
            $zid=$tcatelist->toarray()["data"][0]["son"][0]["cateId"];
        }
    
        $this->assign('tcatelist',$tcatelist);
        $this->assign('zid',$zid);
        $this->assign('item',$item);
        $this->assign('fix',$fix);
        $this->assign('id',$id);
  
        return $this->fetch();

    }
    public function subitem()
    {    
        $id=$this->cateid;
        $item=$this->item;
        $fix=$item["fix"];
        $kzid=$this->request->param('kzid');

        $tcatelist=tcatemodel::getAll(array("parentid"=>$kzid,'limit'=>30),$fix);
        $zid=$tcatelist->toarray()["data"][0]["cateId"];
        $this->assign('tcatelist',$tcatelist);
        $this->assign('zid',$zid);

        $this->assign('item',$item);
        $this->assign('fix',$fix);
        $this->assign('id',$id);
        return $this->fetch();
    }
    public function treeList($zid){

        $item=$this->item;
        $tcatelist=tcatemodel::getAll(array("parentid"=>$zid,'limit'=>30),$item["fix"]);
        $data=$tcatelist->toarray();
        $html='';
     

       // return JsonService::successful('成功', $data["data"]);
        foreach($data["data"] as $k => $v)
		{
			$html=$html.'<div class="kstk-liebiao layui-clear">';
			$html=$html.'<div class="lebiao-jilu">';
			$html=$html.'<div class="jilv-tishu">';
			$html=$html.'<p>总题数：'.$v["nums"].'题</p>';
			$html=$html.'<span class="zuoti-icon" data="'.$v["cateId"].'">开始做题</span>';
			$html=$html.'</div>';
	
			$html=$html.'</div>';
			$html=$html.'<div class="liebiao-title">';
			$html=$html.'<p class="timu-title">'.$v["cateName"].'</p> ';
			$html=$html.'</div>';
			$html=$html.'</div>';
        }
        return JsonService::successful('成功', $html);
    }
    public function texamtemplate()
    {
        $zid=$this->request->param('cateId');
        $item=$this->item;
       
        if(!$this->isopenc)  $this->tquelimit=5;    //没有开通会员只能做5道题
        $data=tque::getAll(array("cateId"=>$zid,'limit'=>$this->tquelimit),$item["fix"]);
    
        $this->assign('cateid',$zid);
        $this->assign('protype',0);
        $this->assign('data',$data);
        $this->assign('item',$item);
        $this->assign('datatotal',count($data->toarray()["data"]));
        return $this->fetch("texamtemplate");
    }
//背题
public function beiti()
{
    $item=$this->item;
    $tcatelist=tcatemodel::getAllarr(array("parentid"=>0,'limit'=>150),$item["fix"]);
   // $list = count($tcatelist) ? $tcatelist->toArray() : [];
    $zhangdata=$this->zhanglist($tcatelist,0,0);

    $redata=Tlianxi::getAll(array("cateid"=>$this->cateid,"userid"=>$this->uid));
    $ldata=[];
    foreach($redata as $key => $items)
    {
        $ldata[$key]["id"]=$items["id"];
        $ldata[$key]["title"]="计划".$key;
        $ldata[$key]["creattime"]=date("Y-m-d",$items["creattime"]);
        $ldata[$key]["typeno"]=0;//当前周key
        $typeno=tlianxi::gettypeno($items["id"]);
        if(!empty($typeno))
        {
            $ldata[$key]["typeno"]=$typeno["typeno"];
        }
       
        $ldata[$key]["upatetime"]=date("Y-m-d",$typeno["updatetime"]);
        $ldata[$key]["isstart"]=0;//当天是否训练完成
        $today=date("Y-m-d",time());
        if($today==$ldata[$key]["upatetime"])
        {
            $ldata[$key]["isstart"]=1;
        }
       
    }
    $this->assign('item',$item);
    $this->assign('cateid',$this->cateid);
    $this->assign('ldata',$ldata);
    $this->assign('data',$zhangdata);
    return $this->fetch();
}
public function getquetypenums()
{
    $item=$this->item;
    $data=$this->request->post();
    $ldata=tque::getQueTypeNums($data["zid"],$item["fix"]);
    return JsonService::successful($ldata);
}
//艾宾浩斯训练计划
public function ab_mnkc(){
    $item=$this->item;
    $data=$this->request->post();
    
    $tquedata=tque::getrank($item["fix"],10,$data["zid"]);

    //新增计划
    $typeno=0;//第N轮数
    $tquelist=json_encode($tquedata);

    $lxdata=array("userid"=>$this->uid,
    "cateid"=>$this->cateid,
    "typeno"=>$typeno,
    "tquelist"=>$tquelist,
    "creattime"=>time(),
    "pid"=>0);//pid 父ID
    
    $total=Tlianxi::gettotal(array("userid"=>$this->uid,"cateid"=>$this->cateid));
   
    if($total>4)
    {
        JsonService::fail('已经创建太多了，不能再创建了');
    }
    $id=Tlianxi::insertdata($lxdata);
    //初始化
    $tdata=array("lianxiid"=>$id,"userid"=>$this->uid,"typeno"=>0,"updatetime"=>'0',"cateid"=>implode(',',$data["zid"]));
    $id=Tlianxi::addtypeno($tdata);

    $redata=Tlianxi::getAll(array("userid"=>$this->uid,"cateid"=>$this->cateid));
    $total=0;
    $html='';
    foreach($redata as $key => $item)
    {
        $isstart=0;
        $today=date("Y-m-d",time());
        $typeno=Tlianxi::gettypeno(array("id"=>$item["id"]));//获取最近的练习
       
        $upatetime=date("Y-m-d",$typeno["updatetime"]);
       
        if($today==$upatetime) $isstart=1;//如果今日做过了就不能再做题了
        
        $html=$html.'<div class="cjjh">';
        $html=$html."计划"."第".$typeno["typeno"]."次".":".date("Y-m-d",$item["creattime"]);
     
        $html=$html.'<span class="zuoti-icon" data-id="'.$item['id'].'" data-typeno="'.$item['typeno'].'" data-isstart="'.$isstart.'">开始做题</span>';
        $html=$html.'<span class="zuoti-icon-del" data="'.$item["id"].'">删除</span></div>';
    }
    return JsonService::successful($html);
 
}
public function dellianxi(){
    $data=$this->request->post();
    Tlianxi::deletedata($data["id"]);
    return JsonService::successful("删除成功");
}
public function GetLXtque(){
    $data=$this->request->post();
 
    $lianxiid=$data["id"];
    $typeno=$data["typeno"];
    $isstart=$data["isstart"];
    $citem=$this->item;

    $typeno++;
    $lxtypeno=tLianxi::gettypeno(array("id"=>$lianxiid));
    tLianxi::updatetypeno($typeno,$this->uid,$lianxiid);

 
    if($typeno>0 && $isstart==0)
    {
        $tquedata=tque::getrank($citem["fix"],10,$lxtypeno["cateid"]);
        $tquelist=json_encode($tquedata);
        $data=array("userid"=>$this->uid,"cateid"=>$this->cateid,"typeno"=>$typeno,"tquelist"=>$tquelist,"creattime"=>time(),"pid"=>$lianxiid);
        $lxid=tLianxi::insertdata($data);//新增
    }
    $rsdata=tLianxi::getlisttque($this->uid,$this->cateid,$typeno,$lianxiid);
    $tquelist=[];
    foreach($rsdata as $key => $item)
    {
        $tque=json_decode($item["tquelist"],TRUE);
        $tquelist=array_merge($tquelist,$tque);
    }
    

    $this->assign('cateid',$this->cateid);
    $this->assign('protype',0);
    $this->assign('data',$tquelist);
    $this->assign('item',$citem);
    $this->assign('datatotal',count($tque));
    return $this->fetch("texamtemplate");

}
public function zhanglist($array, $pid =0,$level=0){
    $list=array();
    foreach ($array as $key => $value){
        if ($value['faId'] == $pid){
            $value['level']=$level;
            $value['son']=$this->zhanglist($array,$value['cateId'],$level+1); //递归获取子记录
            if($value['son'] == null){
                unset($value['son']);//如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
            }
            $list[] = $value; 
            //unset($array[$key]);
        }		
    }
    return $list;
}
//模拟考场
public function mnkc(){
    $item=$this->item;
    $tcatelist=tcatemodel::getAllarr(array("parentid"=>0,'limit'=>150),$item["fix"]);
    $zhangdata=$this->zhanglist($tcatelist,0,0);
    $this->assign('item',$item);
    $this->assign('cateid',$this->cateid);
    $this->assign('data',$zhangdata);
    return $this->fetch();
}
public function mnkctque(){
    $item=$this->item;
    $data=$this->request->post();
 
    if(!$this->isopenc)  $this->tquelimit=5;

    $tquedata=tque::getrank($item["fix"],$this->tquelimit,$data["zid"]);
    $this->assign('cateid',$this->cateid);
    $this->assign('protype',0);
    $this->assign('data',$tquedata);
    $this->assign('item',$item);
    $this->assign('datatotal',count($tquedata));
    return $this->fetch("texamtemplate");
}
//押题
public function yati()
{
    $id=$this->cateid;
    $item=$this->item;
   
    $this->assign('yati',ytcatemodel::getAll(array("proType"=>4,"parentid"=>0,"limit"=>100),$item["fix"]));
    $this->assign('quanti',ytcatemodel::getAll(array("proType"=>9,"parentid"=>0,"limit"=>100),$item["fix"]));
    $this->assign('item',$item);
    $this->assign('id',$id);
    return $this->fetch();
}
public function yttexamtemplate()
{
    $zid=$this->request->param('cateId');
    $item=$this->item;
 

    if(!$this->isopenc)  $this->tquelimit=5;    //没有开通会员只能做5道题

    $data=ytque::getAll(array("cateId"=>$zid,'limit'=>$this->tquelimit),$item["fix"]);

    $this->assign('cateid',$zid);
    $this->assign('protype',1);
    $this->assign('data',$data);
    $this->assign('item',$item);
    $this->assign('datatotal',count($data->toarray()["data"]));
    return $this->fetch("texamtemplate");
}
//题型练习
public function tixinglianxi()
{
    $item=$this->item;
    $this->assign('tdata',tcatemodel::getalltype($item["fix"]));
    $this->assign('ytqtdata',ytcatemodel::getalltype($item["fix"]));
    $this->assign('item',$item);
    return $this->fetch();
}
public function lianxitemplate()
{
    $type=$this->request->param('type');
    $item=$this->item;


    if(!$this->isopenc)  $this->tquelimit=5;
    $data=tque::getAll(array('limit'=>$this->tquelimit,"type"=>$type),$item["fix"]);
    $this->assign('protype',0);
    $this->assign('cateid',0);
    $this->assign('data',$data);
    $this->assign('item',$item);
    $this->assign('datatotal',count($data->toarray()["data"]));
    return $this->fetch("texamtemplate");
}

public function ytlianxitemplate()
{
    $type=$this->request->param('type');
    $item=$this->item;


    if(!$this->isopenc)  $this->tquelimit=5;

    $data=ytque::getAll(array('limit'=>$this->tquelimit,"type"=>$type),$item["fix"]);
    $this->assign('protype',0);
    $this->assign('cateid',0);
    $this->assign('data',$data);
    $this->assign('item',$item);
    $this->assign('datatotal',count($data->toarray()["data"]));
    return $this->fetch("texamtemplate");
}
    //保存收藏
    public function userfav()
    {
        $data=$this->request->post();
      
        $data["cateid"]=$this->cateid;
        $data["userid"]=$this->uid;
       
       
       // return JsonService::successful($data);
        if($data["post"]=='1')
        {
            unset($data["post"]);
            $data["datetime"]=time();
            $dd=Fav::insertdata($data);
        }
        else
        {
            Fav::updatedata($data);
        }
      //  return JsonService::successful($data["post"]=='1');
    }
    //保存笔记
    public function usebiji()
    {
        $data=$this->request->post();
        $data["cateid"]=$this->cateid;
        $data["userid"]=$this->uid;
        $data["datetime"]=time();
        biji::updatedata($data);
    }
    //保存纠错
    public function usejiucuo()
    {
        $data=$this->request->post();
        $data["cateid"]=$this->cateid;
        $data["userid"]=$this->uid;
        $data["datetime"]=time();
        jiucuo::updatedata($data);
    }
    //保存错题
    public function usercuoti()
    {
        $data=json_decode($input=file_get_contents("php://input"),true);
        $list;
        
        foreach ($data["list"] as $key => $item) {
            $list[$key]["cateid"]=$this->cateid;
            $list[$key]["userid"]=$this->uid;
            $list[$key]["zid"]=$data["zid"];
            $list[$key]["datetime"]=time();
            $list[$key]["tqueid"]=$item["tqueid"];
            $list[$key]["uanswer"]=$item["useranswer"];
            $list[$key]["answer"]=$item["answer"];
            $list[$key]["protype"]=$data["protype"];
        }
 
        cuoti::insertall($list);

       // $l=json_decode($data);
        
    }
    
    public function getTree($array, $pid =0,$level=0){
	    $list=array();
		foreach ($array as $key => $value){
			if ($value['parentid'] == $pid){
				$value['level']=$level;
				$value['son']=$this->getTree($array,$value['id'],$level+1); //递归获取子记录
				if($value['son'] == null){
					unset($value['son']);//如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
				}
				$list[] = $value; 
				//unset($array[$key]);
			}		
		}
		return $list;
	}
	public function getTreeson($array)
	{
        $html='';
		foreach ($array as $key => $value){
			if(!empty($value["son"]))
			{
				$html=$html.'<div class="layui-colla-item"><h2 class="layui-colla-title">';
				$html=$html.$value["cname"];
				$html=$html.'</h2><div class="layui-colla-content"> <div class="layui-collapse">';
				$html=$html.$this->getTreeson($value["son"]);
			}
			else
			{
					$html=$html.'<p><a href="javascript:void(0);" class="setKeMu" data-cateid="'.$value["id"].'">';
					$html=$html.$value["cname"];
					$html=$html.'</a></p>';
				continue;
			}
			$html=$html.'</div></div></div>';
		}
		return $html;
	}
}